package com.ssy.lingxi.after.sale.handler.converter;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssy.lingxi.after.sale.model.bo.ReplaceReceiveGoodsBO;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.response.ResponseCode;

import javax.persistence.AttributeConverter;

/**
 *  换货：收货单信息jsonb转化类
 * @author ds
 * @date 2021/8/13
 * @version 2.0.0
 */
public class JpaJsonToReplaceReceiveGoodsBOConverter implements AttributeConverter<ReplaceReceiveGoodsBO, String> {
    private final static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(ReplaceReceiveGoodsBO attribute) {
        try {
            return objectMapper.writeValueAsString(attribute);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR, "权限实体转换Json错误");
        }
    }

    @Override
    public ReplaceReceiveGoodsBO convertToEntityAttribute(String dbData) {
        try {
            if (dbData == null) {
                return null;
            }

            return objectMapper.readValue(dbData, new TypeReference<ReplaceReceiveGoodsBO>() {
            });
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseCode.BUSINESS_ERROR, "数据库json字段转换支付凭证实体错误");
        }
    }
}